package com.edgar.plugin

import com.edgar.plugin.entry.ResourceEntry
import com.edgar.plugin.entry.StyleableEntry
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.ListMultimap
import com.google.common.collect.Lists

public class ResourceCollect{

    File symbolFile
    ListMultimap<String,ResourceEntry> pluginResources = ArrayListMultimap.create()
    List pluginStyleables = Lists.newArrayList()
    int packageId

    ResourceCollect(File symbolFile,int packageId){
        this.symbolFile = symbolFile
        this.packageId = packageId
    }

    void collect(){
        parseResourceEntry()
        reassignPluginResourceId()
    }

    /**
     * 解析R.txt文件
     */
    private void parseResourceEntry(){
        /**
         * int style Base_TextAppearance_AppCompat_Widget_TextView_SpinnerItem 0x7f0c0039
         */
        symbolFile.eachLine { line->
            StringTokenizer tokenizer = new StringTokenizer(line)
            def valueType = tokenizer.nextToken()
            def resourceType = tokenizer.nextToken()
            def resourceName = tokenizer.nextToken()
            def resId = tokenizer.nextToken('\r\n').trim()
            if (resourceType == "styleable"){
                pluginStyleables.add(new StyleableEntry(resourceName,valueType,resId))
            } else {
                pluginResources.put(resourceType,new ResourceEntry(resourceName,resourceType,Integer.decode(resId)))
            }
        }
    }

    /**
     * 重新分配id
     */
    private void reassignPluginResourceId(){
        //The value of aar type should be 1
        def attrTypeId = 1
        //Other types  are allocated from 2
        def lastTypeId = 2
        pluginResources.keySet().each { String resType ->
            def typeId = 0
            def entryId = 0
            if (resType == 'attr') {
                typeId = attrTypeId
            } else {
                typeId = lastTypeId++
            }
            pluginResources.get(resType).each {
                it.setNewResourceId(packageId, typeId, entryId++)
            }
        }
    }

    def getResIdMap() {
        def idMap = [:] as Map<Integer, Integer>
        pluginResources.values().each { resEntry ->
            idMap.put(resEntry.resourceId, resEntry.newResourceId)
        }
        return idMap
    }
}